<template>
  <div class="wait-task-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" class="search-form">
        <el-form-item label="检验编号">
          <el-input v-model="searchParams.waitTaskCode" placeholder="请输入检验编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="searchParams.materialName" placeholder="请输入物料名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="检验类型">
          <el-select v-model="searchParams.waitTaskType" placeholder="请选择检验类型" clearable style="width: 150px;">
            <el-option 
              v-for="item in inspectionTypeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>查询
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <div class="table-header">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          <el-icon>
            <Delete />
          </el-icon>批量删除
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table
        ref="waitTaskTable"
        :data="tableData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
        highlight-current-row
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="waitTaskCode" label="检验编号" width="180"></el-table-column>
        <el-table-column prop="waitTaskType" label="检验类型" width="120"></el-table-column>
        <el-table-column prop="waitTaskTypeDetail" label="详细检验类型" width="150"></el-table-column>
        <el-table-column prop="materialCode" label="物料编码" width="150"></el-table-column>
        <el-table-column prop="materialName" label="物料名称" width="180"></el-table-column>
        <el-table-column prop="num" label="预检数量" width="120"></el-table-column>
        <el-table-column prop="size" label="规格" width="80"></el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleProcess(scope.row)">
              来科检查
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-text">共 {{ total }} 条</span>
        <el-select v-model="pageSize" placeholder="条/页" style="width: 100px">
          <el-option :value="10" label="10条/页"></el-option>
          <el-option :value="20" label="20条/页"></el-option>
          <el-option :value="50" label="50条/页"></el-option>
          <el-option :value="100" label="100条/页"></el-option>
        </el-select>
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
        </el-pagination>
        <span class="page-info">前往 <el-input v-model="goToPage" style="width: 50px;"></el-input> 页</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import http from '@/api/http';
import { Search, Delete, Plus } from '@element-plus/icons-vue';

const router = useRouter();

// API基础路径
const baseApiUrl = '/api/QualityAssurance';

// 加载状态
const loading = ref(false);

// 表格数据
const tableData = ref([]);

// 选中行IDs
const selectedIds = ref([]);

// 分页参数
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const goToPage = ref(1);

// 搜索参数
const searchParams = reactive({
  waitTaskCode: '',
  materialName: '',
  waitTaskType: null
});

// 检验类型选项
const inspectionTypeOptions = [
  { label: '来料检验', value: '来料检验' },
  { label: '制程检验', value: '制程检验' },
  { label: '成品检验', value: '成品检验' }
];

// 获取检验类型显示文本
const getInspectionTypeText = (type) => {
  return type || '未知类型';
};

// 获取状态显示文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '待处理';
    case 1:
      return '处理中';
    case 2:
      return '已完成';
    default:
      return '未知状态';
  }
};

// 获取状态显示类型
const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'info';
    case 1:
      return 'warning';
    case 2:
      return 'success';
    default:
      return 'info';
  }
};

// 加载数据
const fetchData = async () => {
  try {
    loading.value = true;
    
    // 构建查询参数
    const params = {
      PageIndex: currentPage.value,
      PageSize: pageSize.value,
      WaitTaskCode: searchParams.waitTaskCode,
      MaterialName: searchParams.materialName,
      WaitTaskType: searchParams.waitTaskType
    };
    
    // API调用 - 使用POST请求获取检验任务列表
    const response = await http.post(`/api/WaitTask/GetWaitTask`, params);
    console.log(response);
    
    if (response) {
      // 根据API规范，response中应包含rows和total
      tableData.value = response.rows || [];
      total.value = response.total || 0;
    } else {
      ElMessage.error(response?.msg || '获取数据失败');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取数据出错:', error);
    ElMessage.error('获取数据失败，请稍后再试');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchParams).forEach(key => {
    searchParams[key] = '';
  });
  searchParams.waitTaskType = null;
  currentPage.value = 1;
  fetchData();
};

// 表格选择变化
const handleSelectionChange = (rows) => {
  selectedIds.value = rows.map(row => row.id);
};

// 添加来料检验
const handleAddIncoming = () => {
  router.push('/AddIncominginspection');
};

// 处理任务 - 直接跳转到来科检查页面
const handleProcess = (row) => {
  router.push({
    name:"AddIncominginspection",
    query :{
      id:row.materialCode
    }
  });
};

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除此检验任务吗？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    
    // 删除单个检验任务
    const response = await http.post(`${baseApiUrl}/DeleteInspectionTask?ids=${id}`);
    
    if (response && response.status === 0) {
      ElMessage.success('删除成功');
      fetchData();
    } else {
      ElMessage.error(response?.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除出错:', error);
      ElMessage.error('删除失败，请稍后再试');
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条记录？`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    
    // 批量删除检验任务
    const ids = selectedIds.value.join(',');
    const response = await http.post(`${baseApiUrl}/DeleteInspectionTask?ids=${ids}`);
    
    if (response && response.status === 0) {
      ElMessage.success('批量删除成功');
      fetchData();
    } else {
      ElMessage.error(response?.msg || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除出错:', error);
      ElMessage.error('批量删除失败，请稍后再试');
    }
  } finally {
    loading.value = false;
  }
};

// 分页 - 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 分页 - 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData();
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.wait-task-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
}

.total-text {
  margin-right: auto;
  color: #606266;
}

.page-info {
  display: flex;
  align-items: center;
  color: #606266;
}

:deep(.el-tag) {
  text-align: center;
  width: 65px;
}
</style>
